package initializer

import (
	"context"
	"github.com/go-redis/redis/v8"
	"log"
	"sgo/scontext"
	"time"
)

type RedisInitializer struct{}

// 初始化数据校验

func (RedisInitializer) initialize(sc *scontext.SgoContext) error {

	client := redis.NewClient(&redis.Options{
		Addr:         sc.ViperConfig.Redis.Addr,
		Password:     sc.ViperConfig.Redis.Password,
		DB:           sc.ViperConfig.Redis.DB,
		DialTimeout:  sc.ViperConfig.Redis.DialTimeout,
		MaxRetries:   sc.ViperConfig.Redis.MaxRetries,
		ReadTimeout:  sc.ViperConfig.Redis.ReadTimeout * time.Second,
		WriteTimeout: sc.ViperConfig.Redis.WriteTimeout * time.Second,
		PoolSize:     sc.ViperConfig.Redis.PoolSize,
		MinIdleConns: sc.ViperConfig.Redis.MinIdleConns,
	})

	info := client.Info(context.Background())

	if info.Err() != nil {
		log.Println("redis 连接失败：", sc.ViperConfig.Redis.Addr, info.Err().Error())
		return info.Err()
	}

	sc.RedisClient = client
	log.Println("redis 连接成功: ", sc.ViperConfig.Redis.Addr)
	return nil
}
